import 'dart:io';
import 'package:bxultimate/app/theme/app_theme.dart';
import 'package:bxultimate/data/request/base_request.dart';
import 'package:bxultimate/data/store/config_store.dart';
import 'package:bxultimate/domain/intell/IntellPublishDto.dart';
import 'package:bxultimate/resources/assets.dart';
import 'package:bxultimate/shared/shared.dart';
import 'package:bxultimate/shared/util/util_mk.dart';
import 'package:bxultimate/widgets/mk_load_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

class AppUpload extends StatefulWidget {
  final List<Img> imgList;
  final List<String> videoList;

  final int? maxCount;

  const AppUpload({
    super.key,
    required this.imgList,
    required this.videoList,
    this.maxCount
  });

  @override
  State<AppUpload> createState() => _AppUploadState();
}

class _AppUploadState extends State<AppUpload> {
  double itemWidth = (Get.width - AppTheme.iDefaultPadding * 2 - 20) / 3;

  String videoThumbnail = '';

  @override
  Widget build(BuildContext context) {
    return Wrap(
      spacing: 10,
      children: [
        GestureDetector(
          onTap: pickImageOrVideo,
          child: Container(
            width: itemWidth,
            height: itemWidth,
            decoration: BoxDecoration(
              color: Color(0xFFF7F8FA),
            ),
            child: Center(
              child: MkLoadImage(
                Assets.publishCarema,
                width: 24,
              ),
            ),
          ),
        ),
        ...widget.imgList.map((e) => GestureDetector(
              onTap: () {
                TDImageViewer.showImageViewer(
                    context: context,
                    images: [ConfigStore.to.baseFileUrl + e.path!]);
              },
              child: Container(
                width: itemWidth,
                height: itemWidth,
                decoration: BoxDecoration(
                  color: Color(0xFFF7F8FA),
                ),
                child: MkLoadImage(
                  ConfigStore.to.baseFileUrl + e.path!,
                  width: 24,
                ),
              ),
            )),
        ...widget.videoList.map((e) => GestureDetector(
              onTap: () {
                UtilMk.showVideoViewer(
                    ConfigStore.to.baseFileUrl + e, '本地视频', context);
              },
              child: Container(
                width: itemWidth,
                height: itemWidth,
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Image.file(File.fromUri(
                        new Uri(scheme: 'file', path: videoThumbnail))),
                    Positioned(
                      child: Icon(
                        Icons.play_circle,
                        color: Colors.white,
                        size: 30,
                      ),
                    )
                  ],
                ),
              ),
            )),
      ],
    );
  }

  List<String> operationArr = ['拍照', '从本次相册中选择'];

  void pickImageOrVideo() {
    if(widget.maxCount != null && widget.imgList.length >= widget.maxCount!){
      SmartDialog.showToast('最多只能上传${widget.maxCount}张图片或视频');
      return;
    }
    showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return TDAlertDialog.vertical(
            title: '请选择图片或视频',
            showCloseButton: true,
            buttons: [
              TDDialogButtonOptions(
                  title: '拍摄',
                  action: () async {
                    final AssetEntity? entity =
                        await CameraPicker.pickFromCamera(context,
                            pickerConfig:
                                CameraPickerConfig(enableRecording: true));
                    if (entity != null) {
                      upload([entity]);
                    }
                  },
                  theme: TDButtonTheme.primary),
              TDDialogButtonOptions(
                  title: '从手机相册选择',
                  titleColor: TDTheme.of(context).brandColor7,
                  action: () async {
                    final List<AssetEntity>? result =
                        await AssetPicker.pickAssets(context,
                            pickerConfig: AssetPickerConfig(
                              textDelegate: AssetPickerTextDelegate(),
                            ));
                    if (result != null) {
                      upload(result);
                    }
                  },
                  theme: TDButtonTheme.light),
            ]);
      },
    );
  }

  Future<void> upload(List<AssetEntity> assets) async {
    Get.back();
    for (final element in assets) {
      File? file = await element.file;
      var response = await BaseRequest.uploadFile(file!.path);
      bool isImg = await UtilValidate.isImageFile(file);
      if (isImg) {
        setState(() {
          Img img = new Img();
          img.path = response.path;
          img.size = response.size;
          widget.imgList.add(img);
        });
      } else {
        VideoThumbnail.thumbnailFile(
          video: ConfigStore.to.baseFileUrl + response.path!,
          thumbnailPath: (await getTemporaryDirectory()).path,
          maxWidth: itemWidth.toInt(),
          maxHeight: itemWidth.toInt(),
          // specify the height of the thumbnail, let the width auto-scaled to keep the source aspect ratio
          quality: 75,
        ).then((value) {
          setState(() {
            videoThumbnail = value!;
            widget.videoList.add(response.path!);
          });
        });
      }
    }
  }
}
